<template>
    <div class="user-profile">
        <!-- 导航栏 -->
        <van-nav-bar
            title="修改昵称"
            left-text="取消"
            right-text="完成"
            @click-left="$emit('close')"
            @click-right="onClickSave"
        />

        <div class="name-wrap">
            <van-field
                v-model="message"
                rows="2"
                autosize
                type="textarea"
                maxlength="7"
                placeholder="请输入昵称"
                show-word-limit
            />
        </div>
    </div>
</template>

<script>
import { updateUserProfile } from '@/api/user'

export default {
    components: {},
    props: {
        name: {
            type: String,
            required: true
        }
    },
    data () {
        return {
            message: this.name
        }
    },
    created () { },
    computed: {},
    methods: {
        async onClickSave () {
            this.$toast.loading({
                message: '修改中...',
                forbidClick: true
            })
            try {
                // 发起请求
                await updateUserProfile({
                    name: this.message
                })

                // 修改父组件的 name
                this.$emit('update-name', this.message)

                // 关闭弹出层
                this.$emit('close')

                this.$toast.success('修改成功!')
            } catch (error) {
                // console.log(error)
                if (error.response && error.response.status === 409) {
                    this.$toast.fail('昵称已存在!')
                }
            }
        }
    },
    watch: {}
}
</script>

<style scoped>
.user-profile /deep/ .van-nav-bar__text {
    color: #fff;
}
.name-wrap {
    padding: 10px;
}
</style>
